import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { dateFormat, getConfigItem, numberFormat, sortBy, timeFormat, unitShow, UUID } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import { Vue } from 'vue-property-decorator';
import ColumnUtil from '../utils/column-util';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

// 指令管理公共类
export default class InstructionInfoClass extends Vue {
    unitShow = unitShow;
    numberFormat = numberFormat;
    ColumnUtil = new ColumnUtil();

    // 指令信息表分页参数
    pages: pages = {
        pageSize: 50,
        currentPage: 1,
        total: 0,
    };
    // 查询表单
    searchForm: any = {
        assetTypes: [],
        businessType: '',
        directUser: '',
        fundCode: '',
        instNo: '',
        instStatus: '1',
        marketTypes: [],
        orderDirection: '',
        stockCode: '',
        stockType: '',
        stockTypes: [],
        sort: 'D_DIRECT_DATE' + ' ' + 'DESC' + ',' + 'D_DIRECT_TIME' + ' ' + 'DESC',
    };
    // 撤单表单
    cancelOrder: any = {
        cancelOrderType: '2',
        tradeUser: getUser().userCode, // 当前用户
        tradeUserName: getUser().userName, // 当前用户
        orderType: '4',
        instructionType: '10',
        instNo: '',
        originOuterOrderCode: '',
        outerOrderCode: UUID() + '-' + new Date().getTime(),
        requestId: UUID() + '-' + new Date().getTime(),
    };
    dataSource: any[] = []; // 指令信息表数据
    tableKey: number = 0;
    tableColumns: any[] = []; // 指令信息表格全部字段
    // 指令信息表格固定字段
    fixedFieldList: any[] = [
        { content: '指令序号', id: 'instNo', fixed: 'left', minWidth: 120 },
        { content: '产品代码', id: 'fundCode', fixed: 'left', minWidth: 120 },
        { content: '指令状态', id: 'instStatus', fixed: 'right', minWidth: 120 },
        { content: '操作', id: 'operate', fixed: 'right', minWidth: 120 },
    ];
    // 指令信息表格已选择字段列表(不包括固定字段)
    selectedFieldList: any[] = [];
    showFieldList: any[] = []; // 指令信息表格要显示的表格列
    layoutDialog: boolean = false; // 布局设置弹框

    // 指令结果表格相关
    instResultMsg = {
        returnData: {},
        dataKey: 'list',
        title: this.ColumnUtil.instResultColumns,
        checked: { on: false, option: false },
        localSearch: true,
        hidePage: true,
        height: '100%',
    };

    // 指令证券表格相关
    instStockMsg = {
        returnData: { list: [] },
        dataKey: 'list',
        title: this.ColumnUtil.instStockColumns,
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };
    tabsLoading: boolean = false; // 指令结果表格加载状态
    stockLoading: boolean = false; // 指令证券表格加载状态
    tableLoading: boolean = false; // 指令信息表格加载状态

    // 指令状态
    instructionStatus = {
        '0': '已归档',
        '1': '已下达成功',
        '3': '已撤销',
    };
    noData: boolean = true; // 是否有指令数据
    currentClickRow: any = {}; // 点击行对象
    instructionDetail: any = {};
    type: string = ''; // 指令类型--是否历史指令
    sortProp: string = 'directTime'; // 排序字段
    sortOrder: string = 'desc'; // 排序方式
    commonField = this.ColumnUtil.commonFieldSort; // 指令公共排序字段
    extraField: any = {}; // 指令额外排序字段
    instructionInfoUrl: string = ''; // 指令信息请求路径
    directDate: string = ''; // 下达日期
    tableName: string = ''; // 布局表名
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    orderUsers: any[] = []; // 下达人下拉数据
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    stockTypePojo: any = {}; // 证券类别数据
    marketCodes: any = {}; // 交易市场数据
    extraFields: any = {}; // 排序字段

    /* *********** 券商结算相关start *************** */
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY'); // 读取券商结算开关配置
    hideVisible: boolean = true; // 是否隐藏券商结算相关字段
    assetCodeSelectData: any[] = []; // 资产单元编码数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉数据
    /* *********** 券商结算相关end *************** */

    // constructor(instructionInfoUrl: string, searchForm: any) {
    //     super();
    //     this.instructionInfoUrl = instructionInfoUrl;
    //     this.searchForm = searchForm;
    // }

    /**
     * 查询下达人列表
     */
    queryOrderUserList() {
        this.$axios.post('instruction/user/select').then((res: any) => {
            this.orderUsers = res;
        });
    }

    /**
     * 查询证券代码下拉数据
     * @param value 搜索值
     * @param stockCodeUrl 证券代码请求路径
     */
    queryStockCodeList(value: string, stockCodeUrl: string) {
        this.selectLoading = true;
        this.$axios
            .post(stockCodeUrl, {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res || [];
                this.selectLoading = false;
            })
            .catch(() => {
                this.selectLoading = false;
            });
    }

    /**
     * 查询资产单元编码下拉数据
     */
    queryAssetCodeList() {
        this.$axios.get('/asset/list/byFundCode').then((res: any) => {
            this.assetCodeSelectData = res;
        });
    }

    /**
     * 查询组合编码下拉数据
     */
    queryFundAccountCode() {
        this.$axios.get('/fdAc/list/byFundCode').then((res: any) => {
            this.fundAccountCodeSelectData = res;
        });
    }

    /**
     * 按钮点击事件
     * @param action 点击按钮（布局设置按钮、查询条件展开按钮、查询按钮）
     */
    handleButtonClick(action: string): void {
        if (action === 'layout') {
            this.layoutDialog = true;
        } else if (action === 'hide') {
            this.hideVisible = !this.hideVisible;
        } else if (action == 'search') {
            this.handleQueryClick();
        }
    }

    /**
     * 查询按钮点击
     */
    handleQueryClick() {
        this.searchForm.directDate = Number(this.directDate) || null;
        this.currentClickRow = {};
        this.getInstruction(this.searchForm, { currentPage: 1, pageSize: 50 });
    }

    /**
     * 查询指令信息
     * @param param 查询表单
     * @param pages 分页参数
     */
    getInstruction(param: any, pages: any) {
        this.tableLoading = true;
        this.$axios
            .post(this.instructionInfoUrl, {
                ...this.searchForm,
                paging: {
                    currentPage: pages.currentPage,
                    pageSize: pages.pageSize,
                },
            })
            .then((res: any) => {
                this.dataSource = res.list;
                this.pages.total = res.total;
                if (this.dataSource.length) {
                    this.currentClickRow = this.dataSource[0] || {};
                    if (this.currentClickRow.instStatus == '0') {
                        this.type = 'history';
                    } else {
                        this.type = '';
                    }
                    (this.$refs['table'] as any).setCurrentRow(this.dataSource[0]);
                    this.handleRow({ row: this.currentClickRow });
                    this.noData = false;
                } else {
                    this.$set(this.instStockMsg.returnData, 'list', []);
                    this.$set(this.instResultMsg.returnData, 'list', []);
                    this.noData = true;
                }
                this.tableLoading = false;
            })
            .catch(() => {
                this.tableLoading = false;
            });
    }

    /**
     * 指令信息表格分页事件 el-pagination组件
     * @param curPage 当前页
     */
    handleCurrentChange(curPage: number): void {
        this.pages.currentPage = curPage;
        this.getInstruction(this.searchForm, this.pages);
    }

    /**
     * 指令信息表格排序变化事件
     * @param column
     */
    changeTableSort(column: any): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        const sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        if (sortType) {
            this.searchForm.sort = this.findName(column.property, sortType);
        } else {
            this.searchForm.sort = 'D_DIRECT_DATE ' + 'DESC' + ',' + 'D_DIRECT_TIME ' + 'DESC';
        }
        this.getInstruction(this.searchForm, { currentPage: 1, pageSize: 50 });
    }

    /**
     * 获取排序字段名称
     * @param flied 排序字段
     * @param order 排序类型
     * @returns
     */
    findName(flied: string, order: string): string {
        let value = '';
        let field = '';
        const allFields = { ...this.commonField, ...this.extraFields };
        if (flied === 'directTime') {
            value = 'D_DIRECT_DATE' + ' ' + order + ',' + 'D_DIRECT_TIME' + ' ' + order;
        } else {
            for (const key in allFields) {
                if (flied === key) {
                    field = allFields[key];
                }
            }
            value = field + ' ' + order;
        }
        return value;
    }

    // 格式化日期
    formatterDate(cellValue) {
        return cellValue ? dateFormat(cellValue) : '';
    }

    //  格式化时间
    formatterTime(cellValue) {
        return cellValue ? timeFormat(cellValue) : '';
    }

    /**
     * 修改按钮点击事件
     * @param row 点击行
     */
    handleUpdateInst(row: any) {
        this.$emit('changeTab', row);
    }

    /**
     * 撤单按钮点击事件
     * @param row 点击行
     */
    handleBtnDel(row: any): void {
        this.cancelOrder.instNo = row.instNo;
        this.cancelOrder.originOuterOrderCode = row.outerOrderCode;
        this.$confirm('确认是否撤单?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(() => {
                this.$axios
                    .post('/dataEngine/order/cancelOrder', this.cancelOrder)
                    .then((res: any) => {
                        this.yh_message_success('撤单成功');
                        this.getInstruction(this.searchForm, { currentPage: 1, pageSize: this.pages.pageSize });
                    })
                    .catch(() => {
                        this.yh_message_error('撤单失败');
                    });
            })
            .catch(() => {
                this.yh_message_info('已取消撤单');
            });
    }

    /**
     * 指令信息表格操作栏按钮禁用事件
     * @param row 行数据
     * @returns
     */
    handleDisabled(row: any): boolean {
        const userCode = getUser().userCode;
        return !(row['instStatus'] == '1' && (userCode == row.directUser || getUser().superuser));
    }

    /**
     * 指令信息表格行点击事件
     * @param row 点击行
     */
    handleRow(row): void {
        if (row.instStatus == '0') {
            this.type = 'history';
        } else {
            this.type = '';
        }
        this.getInstructionInfo();
    }

    /**
     * 查询指令证券和指令结果
     */
    getInstructionInfo() {
        this.tabsLoading = true;
        this.stockLoading = true;
        const form = {
            serialNo: this.currentClickRow.serialNo, // 流水号
            instNo: this.currentClickRow.instNo, // 指令序号
            outOrderCode: this.currentClickRow.outerOrderCode, // 外部指令序号
            showError: true, // 产品true, 浦银false
            dailyInstructionNo: 0, // 恒生指令序号
            indexDailyModify: 0, // 恒生指令修改次序
            sourceType: 1, // 数据来源类型 (判断是否外部指令下达) 这里默认查询内部的指令
        };

        let url = '';
        if (this.type === 'history') {
            url = '/instruction/inst/history/all/new';
        } else {
            url = '/instruction/inst/all/new';
        }
        // if (this.type === 'history') {
        //     url = '/instruction/inst/history/all/' + this.currentClickRow.instNo + '/' + this.currentClickRow.outerOrderCode;
        // } else {
        //     url = '/instruction/inst/all/' + this.currentClickRow.instNo + '/' + this.currentClickRow.outerOrderCode;
        // }
        this.$axios.post(url, form).then((res: any) => {
            let instStockDataSource = [];
            let instResultDataSource = [];
            if (res.deposits && res.deposits.length > 0) {
                instStockDataSource = instStockDataSource.concat(res.deposits);
            }
            if (res.repos && res.repos.length > 0) {
                instStockDataSource = instStockDataSource.concat(res.repos);
            }
            if (res.stocks && res.stocks.length > 0) {
                instStockDataSource = instStockDataSource.concat(res.stocks);
            }
            instStockDataSource.forEach((item, i) => (item.key = item.serialNo + '-' + i));
            if (res.pleds && res.pleds.length > 0) {
                res.pleds.forEach((item, i) => (item.key = item.serialNo + '-' + i));
            }
            if (res.results && res.results.length > 0) {
                res.results.forEach((item, i) => (item.key = item.entryCode + '-' + i));
                res.results = res.results.sort(sortBy('thresholdType', 'desc'));
            }
            this.tabsLoading = false;
            this.stockLoading = false;
            this.$set(this.instStockMsg.returnData, 'list', instStockDataSource);
            this.instStockMsg.returnData.list.forEach(ele => {
                ele.marketCode = this.marketCodes[ele.marketCode];
            });
            instResultDataSource = res.results;
            // instResultDataSource = res.results.filter((itme: any) => itme.thresholdType !== '4');
            this.$set(this.instResultMsg.returnData, 'list', instResultDataSource);
        });
    }

    /**
     * 指令结果表查看按钮点击事件
     * @param obj 点击行
     */
    handleBtnLook(obj: any): void {
        this.$emit('handelOperate', { record: obj.row, history: this.type === 'history', clickRecord: this.currentClickRow });
    }

    /**
     * 布局提交回调事件
     * @param data
     */
    onSubmit(data) {
        this.queryLayout();
    }

    /**
     * 查询页面布局信息
     */
    async queryLayout() {
        const resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/' + this.tableName)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        } else {
            this.showFieldList = this.tableColumns;
            this.selectedFieldList = this.tableColumns;
        }
        this.tableKey++;
    }
}
